﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeTop.CodeTop
{
    public class Solution56
    {
        public int[][] Merge(int[][] intervals)
        {

            Array.Sort(intervals,MyCompare);

            IList<IList<int>> res = new List<IList<int>>();



            int intervalslen = intervals.Length;
            if (intervalslen == 1)
            {
                return intervals;
            }
           
            for(int i = 1;i< intervalslen;i++)
            {
                int[] pre = intervals[i-1];

                int[] cur = intervals[i ];

                if (pre[1] >= cur[0])
                {
                    //合并

                    intervals[i][0] = Math.Min(cur[0], pre[0]);
                    intervals[i][1] = Math.Max(cur[1], pre[1]);


                }
                else
                {
                    IList<int> path = new List<int>(pre);
                   
                    res.Add(path);
                }
              
            }
            res.Add(intervals[intervalslen-1]);


            int[][] result = new int[res.Count][];
            for (int j = 0; j < res.Count; j++)
            {


    
                result[j]= res[j].ToArray();
            }
            return result;



        }

        private int MyCompare(int[] x, int[] y)
        {
           return x[0].CompareTo(y[0]);  
        }
    }
}
